<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <div class="header-decoration-left"></div>
      <div class="dashboard-title">自动生产线看板</div>
      <div class="header-decoration-right"></div>
      <div class="dashboard-time">{{ currentTime }}</div>
    </div>
    
    <div class="dashboard-content">
      <!-- 加载计划区域 -->
      <div class="load-plan-container">
        <div class="plan-input-area">
          <input type="text" class="plan-input" placeholder="" readonly>
        </div>
        <button class="plan-button">加载计划</button>
      </div>

      <!-- 三个主要区域 -->
      <div class="main-layout">
        <!-- 左侧区域 (红色框) -->
        <div class="left-section">
          <!-- 一周不良品统计 -->
          <div class="chart-card">
            <div class="card-title">一周不良品统计</div>
            <div ref="defectChart" class="chart"></div>
          </div>

          <!-- 关键工序和当日生产率评估 (左右布局) -->
          <div class="process-rate-row">
            <!-- 关键工序 -->
            <div class="chart-card">
              <div class="card-title">关键工序</div>
              <div ref="keyProcessChart" class="chart"></div>
            </div>

            <!-- 当日生产率评估 -->
            <div class="info-card">
              <div class="card-title">当日生产率评估</div>
              <div class="production-rate">
                <div class="rate-item">
                  <span class="rate-dot success"></span>
                  <span>实际完成率 {{ productionRate.actual }}%</span>
                </div>
                <div class="rate-item">
                  <span class="rate-dot warning"></span>
                  <span>期望完成率 {{ productionRate.target }}%</span>
                </div>
                <div class="rate-item">
                  <span class="rate-dot danger"></span>
                  <span>单件耗时 {{ unitTime }}</span>
                </div>
                <div class="rate-item">
                  <span class="rate-dot info"></span>
                  <span>标准耗时 {{ standardTime }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 一周产量均差 -->
          <div class="chart-card">
            <div class="card-title">一周产量均差</div>
            <div ref="productionDiffChart" class="chart"></div>
          </div>
        </div>

        <!-- 中间区域 (蓝色框) -->
        <div class="center-section">
          <!-- 上排：订单总体进度 和 订单今日进度 -->
          <div class="progress-row">
            <!-- 订单总体进度 -->
            <div class="chart-card">
              <div class="card-title">订单总体进度</div>
              <div class="progress-chart-wrapper">
                <div class="progress-chart-container">
                  <div ref="totalProgressChart" class="chart-small"></div>
                  <div class="progress-center-text">
                    <div class="center-label">已生产</div>
                  </div>
                </div>
                <div class="progress-info">
                  <div class="info-left">
                    <div>总体计划 {{ totalOrderStats.totalPlan }}</div>
                    <div>不良品 {{ totalOrderStats.defects }}</div>
                  </div>
                  <div class="info-right">
                    <div>已经生产 {{ totalOrderStats.produced }}</div>
                    <div>完成率 {{ totalOrderStats.completionRate }}%</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单今日进度 -->
            <div class="chart-card">
              <div class="card-title">订单今日进度</div>
              <div class="progress-chart-wrapper">
                <div class="progress-chart-container">
                  <div ref="todayProgressChart" class="chart-small"></div>
                  <div class="progress-center-text">
                    <div class="center-label">已生产</div>
                  </div>
                </div>
                <div class="progress-info">
                  <div class="info-left">
                    <div>今日计划 {{ todayOrderStats.todayPlan }}</div>
                    <div>不良品 {{ todayOrderStats.todayDefects }}</div>
                  </div>
                  <div class="info-right">
                    <div>已经生产 {{ todayOrderStats.todayProduced }}</div>
                    <div>良品率 {{ todayOrderStats.qualityRate }}%</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 下排：近期生产计划列表 -->
          <div class="table-card large">
            <div class="card-title">近期生产计划列表</div>
            <div class="table-container scrolling-table">
              <div class="table-header">
                <div class="table-header-row">
                  <div class="header-cell">订单</div>
                  <div class="header-cell">数量</div>
                  <div class="header-cell">开始</div>
                  <div class="header-cell">结束</div>
                  <div class="header-cell">状态</div>
                  <div class="header-cell">进度</div>
                </div>
              </div>
              <div class="table-body">
                <div class="scrolling-content">
                  <div v-for="plan in duplicatedPlans" :key="`${plan.id}-${plan.duplicate}`" class="table-row">
                    <div class="table-cell">{{ plan.orderId }}</div>
                    <div class="table-cell">{{ plan.quantity }}</div>
                    <div class="table-cell">{{ formatDate(plan.startTime) }}</div>
                    <div class="table-cell">{{ formatDate(plan.endTime) }}</div>
                    <div class="table-cell" :class="plan.status">{{ plan.statusText }}</div>
                    <div class="table-cell">{{ plan.completionRate }}%</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧区域 (橙色框) -->
        <div class="right-section">
          <!-- 当前班组 -->
          <div class="info-card">
            <div class="card-title">当前班组</div>
            <div class="team-info">
              <template v-if="getCurrentTeamInfo">
                <p>名称 {{ getCurrentTeamInfo.name }}</p>
                <p>人数 {{ getCurrentTeamInfo.memberCount }}</p>
                <p>负责人 {{ getCurrentTeamInfo.leader }}</p>
                <p>电话 {{ getCurrentTeamInfo.phone }}</p>
                <p v-if="getCurrentTeamInfo.shiftType">班次 {{ getShiftTypeName(getCurrentTeamInfo.shiftType) }}</p>
              </template>
              <template v-else>
                <div class="no-team-info">
                  <p>━━━━━━━━━━━━━━</p>
                  <p style="text-align: center; color: rgba(255, 255, 255, 0.5); font-size: 14px;">当前时间段无班组生产</p>
                  <p>━━━━━━━━━━━━━━</p>
                </div>
              </template>
            </div>
          </div>

          <!-- 异常列表 -->
          <div class="info-card">
            <div class="card-title">异常列表</div>
            <div class="exception-list">
              <div v-for="exception in exceptions" :key="exception.id" class="exception-item">
                {{ exception.content }}
              </div>
            </div>
          </div>

          <!-- 最近生产产品列表 -->
          <div class="table-card">
            <div class="card-title">最近生产产品列表</div>
            <div class="product-list">
              <div class="table-header-row">
                <span>产品</span>
                <span>产品品质</span>
                <span>生产时间</span>
              </div>
              <div v-for="product in recentProducts" :key="product.id" class="product-item">
                <span>{{ product.serialNo }}</span>
                <span :class="product.quality">{{ product.qualityText }}</span>
                <span>{{ formatDate(product.productionTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, reactive, watch } from 'vue'
import * as echarts from 'echarts'
import type { EChartsType } from 'echarts'
import http from '@/api/http'

// 类型定义
interface TeamInfo {
  name: string
  memberCount: number
  leader: string
  phone: string
}

interface Exception {
  id: number
  content: string
}

interface ProductionRate {
  actual: number
  target: number
}

interface ProductionPlan {
  id: number
  orderId: string
  quantity: number
  startTime: Date
  endTime: Date
  status: string
  statusText: string
  completionRate: number
  duplicate?: number
}

interface Product {
  id: number
  serialNo: string
  quality: string
  qualityText: string
  productionTime: Date
}

// 工单台账数据类型（根据用户提供的完整字段列表）
interface TicketLedgerData {
  tickeId: number               // 主键Id   
  tickeNumber: string           // 工单编号 
  line: string                  // 工艺线路
  plan: number                  // 计划数量 
  stateTime: string             // 开始时间 
  endTime: string               // 结束时间
  bomcode: string               // Bom编码  
  qRCode?: string               // 二维码
  produce: number               // 已经生产 
  defectiveProduct?: number     // 不良品
  firstPassRate?: number        // 一次通过率
  orderFulfillmentRate?: number // 订单履行率
  remark?: string               // 备注
  ordersState: number           // 订单状态 (0=创建, 1=进行中, 2=已完成)
  createTime: string            // 创建时间
  [key: string]: any
}

// 根据用户提供的准确字段信息定义类型（API返回小写开头）
interface TeamScheduleData {
  dailId: number
  planCode: string
  orderCode: string
  line: string
  targetTime: string
  yield: number
  actual: number
  defective: number
  passRate: number
  actualTake: number
  team: string
  // API返回的字段名（首字母小写）
  morningshiftStarttim: string | null      // 早班开始时间（注意：没有e）
  morningshiftEndtime: string | null       // 早班结束时间
  firstmorningShiftStarttime: string | null // 早班1开始时间
  firstmorningShiftEndtime: string | null   // 早班1结束时间
  middleShiftStartTime: string | null       // 中班开始时间
  middleShiftEndTime: string | null         // 中班结束时间
  firstmiddleShiftStartTim: string | null   // 中班1开始时间（注意：Tim不是Time）
  firstmiddleShiftEndTime: string | null    // 中班1结束时间
  eveningShiftStartTime: string | null      // 晚班开始时间
  eveningShiftEndTime: string | null        // 晚班结束时间
  firsteveningShiftStartTime: string | null // 晚班1开始时间
  firsteveningShiftEndTime: string | null   // 晚班1结束时间
  calibratedTimePerPiece: number            // 注意：可能是这个字段名
  actualTimePerPiece: number                // 注意：可能是这个字段名
  teamId: number
  teamName: string | null
  duty: string
  phone: string
  teamNum: number
  // 添加索引签名以允许任意属性
  [key: string]: any
}

// 报工信息数据类型
interface SigningWorkData {
  signingId: number          // 主键Id         
  signingCode: string        // 报工编码       
  orderCode: string          // 订单编号       
  planCode: string           // 计划编码       
  signingNumber: number      // 报工数量       
  defective: number          // 次品数量       
  productionTime: number     // 生产耗时（分钟）
  createTime: string         // 创建时间       
  [key: string]: any
}

// 工单工艺路线数据类型（根据实际API返回数据）
interface TicketLedgerOperationalData {
  tickeId: number               // 主键Id
  tickeNumber: string           // 工单编号 
  line: string                  // 工艺线路
  plan: number                  // 计划数量 
  stateTime: string             // 开始时间 
  endTime: string               // 结束时间
  bomcode: string               // Bom编码  
  qrCode?: string               // 二维码
  produce: number               // 已经生产 
  defectiveProduct?: number     // 不良品
  firstPassRate?: number        // 一次通过率
  orderFulfillmentRate?: number // 订单履行率
  remark?: string               // 备注
  ordersState: number           // 订单状态 
  routingId: number             // 路由ID
  routing?: string              // 路由
  processDescription: string    // 流程描述 
  processTiming: string         // 流程时序 
  [key: string]: any
}

// 响应式数据
const currentTime = ref('2025年6月7日-9时57分42秒')
const teamInfo = ref<TeamInfo>({
  name: '磁阻2线1班',
  memberCount: 5,
  leader: '赵欢',
  phone: '18665802636'
})

const exceptions = ref<Exception[]>([
  { id: 1, content: '压接端子' },
  { id: 2, content: '焊线' },
  { id: 3, content: '绕线' },
  { id: 4, content: '点胶' }
])

// 从班组数据中计算当日生产率评估
const productionRateStats = computed(() => {
  if (!getNowTeamledgerData.value || getNowTeamledgerData.value.length === 0) {
    return {
      actual: 10,
      target: 20,
      unitTime: '32',
      standardTime: '30'
    }
  }

  // 获取当天的班组数据
  const today = new Date().toISOString().slice(0, 10)
  const todayTeamData = getNowTeamledgerData.value.filter(item => {
    if (!item.targetTime) return false
    const itemDate = new Date(item.targetTime).toISOString().slice(0, 10)
    return itemDate === today
  })

  if (todayTeamData.length === 0) {
    // 如果没有今天的数据，使用全部数据
    const allData = getNowTeamledgerData.value
    if (allData.length > 0) {
      const latestData = allData[0] // 使用最新的一条数据
      
      const planProduction = latestData.yield || 0      // 计划产量
      const actualProduction = latestData.actual || 0   // 实际产量
      const actualCompletionRate = planProduction > 0 ? Math.round((actualProduction / planProduction) * 100) : 0
      const passRate = latestData.passRate || 0         // 一次通过率
      const actualTimePerPiece = latestData.actualTimePerPiece || latestData.actualTake || 32  // 实际每件耗时
      const calibratedTimePerPiece = latestData.calibratedTimePerPiece || 30  // 标定每件耗时

      console.log('使用最新班组数据计算生产率:', {
        计划产量: planProduction,
        实际产量: actualProduction,
        实际完成率: actualCompletionRate,
        一次通过率: passRate,
        实际耗时: actualTimePerPiece,
        标定耗时: calibratedTimePerPiece
      })

      return {
        actual: actualCompletionRate,
        target: Math.round(passRate),
        unitTime: actualTimePerPiece.toString(),
        standardTime: calibratedTimePerPiece.toString()
      }
    }
  } else {
    // 使用今天的数据计算
    const totalPlan = todayTeamData.reduce((sum, item) => sum + (item.yield || 0), 0)
    const totalActual = todayTeamData.reduce((sum, item) => sum + (item.actual || 0), 0)
    const avgPassRate = todayTeamData.reduce((sum, item) => sum + (item.passRate || 0), 0) / todayTeamData.length
    const avgActualTime = todayTeamData.reduce((sum, item) => sum + (item.actualTimePerPiece || item.actualTake || 0), 0) / todayTeamData.length
    const avgCalibratedTime = todayTeamData.reduce((sum, item) => sum + (item.calibratedTimePerPiece || 0), 0) / todayTeamData.length

    const actualCompletionRate = totalPlan > 0 ? Math.round((totalActual / totalPlan) * 100) : 0

    console.log('使用今日班组数据计算生产率:', {
      今日计划: totalPlan,
      今日实际: totalActual,
      实际完成率: actualCompletionRate,
      平均通过率: avgPassRate,
      平均实际耗时: avgActualTime,
      平均标定耗时: avgCalibratedTime
    })

    return {
      actual: actualCompletionRate,
      target: Math.round(avgPassRate),
      unitTime: Math.round(avgActualTime).toString(),
      standardTime: Math.round(avgCalibratedTime).toString()
    }
  }

  // 默认值
  return {
    actual: 10,
    target: 20,
    unitTime: '32',
    standardTime: '30'
  }
})

// 保持原有的ref结构以兼容模板
const productionRate = computed(() => ({
  actual: productionRateStats.value.actual,
  target: productionRateStats.value.target
}))

const unitTime = computed(() => productionRateStats.value.unitTime)
const standardTime = computed(() => productionRateStats.value.standardTime)

const productionPlans = ref<ProductionPlan[]>([
  {
    id: 1,
    orderId: '23',
    quantity: 12,
    startTime: new Date('2025-06-06 14:38:00'),
    endTime: new Date('2025-06-27 14:38:00'),
    status: 'in-progress',
    statusText: '订单结束',
    completionRate: 0
  },
  {
    id: 2,
    orderId: '1',
    quantity: 1,
    startTime: new Date('2025-06-14 16:01:00'),
    endTime: new Date('2025-05-30 16:01:00'),
    status: 'created',
    statusText: '创建',
    completionRate: 1
  },
  {
    id: 3,
    orderId: '123',
    quantity: 123,
    startTime: new Date('2025-05-30 01:44:00'),
    endTime: new Date('2025-05-02 01:44:00'),
    status: 'completed',
    statusText: '',
    completionRate: 0
  },
  {
    id: 4,
    orderId: '20250527',
    quantity: 1000,
    startTime: new Date('2025-05-27 14:44:00'),
    endTime: new Date('2025-05-27 17:44:00'),
    status: 'in-progress',
    statusText: '订单结束',
    completionRate: 100
  },
  {
    id: 5,
    orderId: 'DD202408902',
    quantity: 1000,
    startTime: new Date('2024-08-10 08:13:00'),
    endTime: new Date('2024-08-11 08:13:00'),
    status: 'in-progress',
    statusText: '进行中',
    completionRate: 64
  },
  {
    id: 6,
    orderId: 'DD202408901',
    quantity: 1000,
    startTime: new Date('2024-08-09 20:55:00'),
    endTime: new Date('2024-08-12 20:55:00'),
    status: 'in-progress',
    statusText: '进行中',
    completionRate: 100
  }
])



// 静态数据作为备用
const staticProducts = ref<Product[]>([
  {
    id: 1,
    serialNo: 'P202306070001',
    quality: 'good',
    qualityText: '合格',
    productionTime: new Date('2023-06-07 09:15:00')
  },
  {
    id: 2,
    serialNo: 'P202306070002',
    quality: 'defect',
    qualityText: '不合格',
    productionTime: new Date('2023-06-07 09:20:00')
  },
  {
    id: 3,
    serialNo: 'P202306070003',
    quality: 'good',
    qualityText: '合格',
    productionTime: new Date('2023-06-07 09:25:00')
  },
  {
    id: 4,
    serialNo: 'P202306070004',
    quality: 'good',
    qualityText: '合格',
    productionTime: new Date('2023-06-07 09:30:00')
  },
  {
    id: 5,
    serialNo: 'P202306070005',
    quality: 'defect',
    qualityText: '不合格',
    productionTime: new Date('2023-06-07 09:35:00')
  }
])

// 基于工单工艺路线数据的最近生产产品列表
const recentProducts = computed(() => {
  if (!GetTicketLedgerOperationalData.value || GetTicketLedgerOperationalData.value.length === 0) {
    console.log('工单工艺路线数据为空，使用静态产品数据')
    return staticProducts.value
  }

  console.log('开始处理工单工艺路线数据为产品列表，总记录数:', GetTicketLedgerOperationalData.value.length)

  // 转换工单工艺路线数据为产品列表格式
  const products: Product[] = []
  
  GetTicketLedgerOperationalData.value
    .filter(ticket => ticket.produce > 0) // 只显示有生产数量的工单
    .forEach((ticket, index) => {
      const produceCount = ticket.produce || 0
      const defectCount = ticket.defectiveProduct || 0
      
      // 使用line字段作为产品名称
      const productName = ticket.line || `产品${ticket.tickeId}`
      
      // 使用开始时间作为生产时间
      const productionTime = ticket.stateTime ? new Date(ticket.stateTime) : new Date()
      
      // 获取工艺流程信息
      const processTiming = ticket.processTiming || ''
      const processDescription = ticket.processDescription || ''
      
      // 判断产品品质：如果有不良品，显示不合格，否则显示合格
      const hasDefects = defectCount > 0
      const quality = hasDefects ? 'defect' : 'good'
      const qualityText = hasDefects ? '不合格' : '合格'
      
      console.log(`工单${index + 1}:`, {
        工单号: ticket.tickeNumber,
        产品名称: productName,
        已生产: produceCount,
        不良品: defectCount,
        品质: qualityText,
        开始时间: productionTime,
        工艺流程: processTiming,
        流程描述: processDescription
      })

      // 每个工单只生成一条产品记录
      products.push({
        id: ticket.tickeId,
        serialNo: productName,
        quality: quality,
        qualityText: qualityText,
        productionTime: productionTime
      })
    })

  // 按生产时间倒序排列，并只显示最近的15个产品
  const sortedProducts = products
    .sort((a, b) => b.productionTime.getTime() - a.productionTime.getTime())
    .slice(0, 15)

  console.log('最终产品列表:', sortedProducts)

  return sortedProducts.length > 0 ? sortedProducts : staticProducts.value
})

// Chart refs
const defectChart = ref<HTMLElement | null>(null)
const totalProgressChart = ref<HTMLElement | null>(null)
const todayProgressChart = ref<HTMLElement | null>(null)
const keyProcessChart = ref<HTMLElement | null>(null)
const productionDiffChart = ref<HTMLElement | null>(null)

// Chart instances
let defectChartInstance: EChartsType | null = null
let totalProgressChartInstance: EChartsType | null = null
let todayProgressChartInstance: EChartsType | null = null
let keyProcessChartInstance: EChartsType | null = null
let productionDiffChartInstance: EChartsType | null = null

// 工具函数
const formatDate = (date: Date): string => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 初始化图表
const initDefectChart = () => {
  if (!defectChart.value) return
  defectChartInstance = echarts.init(defectChart.value)
  updateDefectChart()
}

const updateDefectChart = () => {
  if (!defectChartInstance) return
  
  const stats = weeklyDefectStats.value
  const maxValue = Math.max(...stats.defectCounts, 5) // 确保最小刻度为5
  
  defectChartInstance.setOption({
    grid: {
      top: '10%',
      left: '8%',
      right: '8%',
      bottom: '25%'
    },
    xAxis: {
      type: 'category',
      data: stats.dates,
      axisLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.3)'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.65)',
        fontSize: 10,
        rotate: 0,
        margin: 5,
        interval: 0
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.3)'
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: maxValue,
      splitLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.1)',
          type: 'dashed'
        }
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.65)',
        fontSize: 12
      }
    },
    series: [{
      data: stats.defectCounts,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        color: '#00d4ff',
        width: 2
      },
      itemStyle: {
        color: '#00d4ff'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(0, 212, 255, 0.3)'
          }, {
            offset: 1,
            color: 'rgba(0, 212, 255, 0)'
          }]
        }
      }
    }]
  })
}

const initTotalProgressChart = () => {
  if (!totalProgressChart.value) return
  totalProgressChartInstance = echarts.init(totalProgressChart.value)
  updateTotalProgressChart()
}

const updateTotalProgressChart = () => {
  if (!totalProgressChartInstance) return
  
  const stats = totalOrderStats.value
  const remaining = Math.max(0, stats.totalPlan - stats.produced)
  
  totalProgressChartInstance.setOption({
    series: [{
      type: 'pie',
      radius: ['50%', '70%'],
      center: ['50%', '50%'],
      startAngle: 90,
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      data: [
        { 
          value: stats.produced, 
          name: '已生产',
          itemStyle: { 
            color: '#52c41a',
            borderRadius: 8,
            borderColor: '#52c41a',
            borderWidth: 1
          }
        },
        { 
          value: remaining, 
          name: '未生产',
          itemStyle: { 
            color: '#1890ff',
            borderRadius: 8,
            borderColor: '#1890ff',
            borderWidth: 1
          }
        }
      ],
      emphasis: {
        disabled: true
      },
      silent: true
    }]
  })
}

const initTodayProgressChart = () => {
  if (!todayProgressChart.value) return
  todayProgressChartInstance = echarts.init(todayProgressChart.value)
  updateTodayProgressChart()
}

const updateTodayProgressChart = () => {
  if (!todayProgressChartInstance) return
  
  const stats = todayOrderStats.value
  const remaining = Math.max(0, stats.todayPlan - stats.todayProduced)
  
  todayProgressChartInstance.setOption({
    series: [{
      type: 'pie',
      radius: ['50%', '70%'],
      center: ['50%', '50%'],
      startAngle: 90,
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      data: [
        { 
          value: stats.todayProduced, 
          name: '已生产',
          itemStyle: { 
            color: '#52c41a',
            borderRadius: 8,
            borderColor: '#52c41a',
            borderWidth: 1
          }
        },
        { 
          value: remaining, 
          name: '未生产',
          itemStyle: { 
            color: '#1890ff',
            borderRadius: 8,
            borderColor: '#1890ff',
            borderWidth: 1
          }
        }
      ],
      emphasis: {
        disabled: true
      },
      silent: true
    }]
  })
}

const initKeyProcessChart = () => {
  if (!keyProcessChart.value) return
  keyProcessChartInstance = echarts.init(keyProcessChart.value)
  updateKeyProcessChart()
}

const updateKeyProcessChart = () => {
  if (!keyProcessChartInstance) return
  
  const stats = processTimingStats.value
  const maxValue = Math.max(...stats.counts, 10) // 确保最小刻度为10
  
  keyProcessChartInstance.setOption({
    tooltip: {
      show: true,
      confine: true,
      backgroundColor: 'rgba(10, 47, 90, 0.95)',
      borderColor: 'rgba(0, 212, 255, 0.6)',
      borderWidth: 2,
      borderRadius: 8,
      padding: [12, 16],
      textStyle: {
        color: '#ffffff',
        fontSize: 12
      },
      shadowBlur: 10,
      shadowColor: 'rgba(0, 0, 0, 0.5)',
      position: function(pos: any, params: any, dom: any, rect: any, size: any) {
        // 自动调整位置，确保tooltip完全显示在容器内
        const obj: any = { top: 10 }
        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30
        return obj
      },
      formatter: function(params: any) {
        let result = `<div style="font-weight: bold; color: #00d4ff; margin-bottom: 8px; font-size: 13px; text-align: center;">关键工序统计</div>`
        
        // 显示所有工序的统计信息，使用表格式布局
        result += `<table style="width: 100%; border-collapse: collapse; margin: 0;">`
        
        stats.processes.forEach((process, index) => {
          if (index < stats.counts.length) {
            const count = stats.counts[index]
            const percentage = maxValue > 0 ? ((count / maxValue) * 100).toFixed(1) : '0.0'
            
            result += `<tr style="border-bottom: 1px solid rgba(0, 212, 255, 0.2);">
              <td style="padding: 4px 8px 4px 0; color: rgba(255, 255, 255, 0.9); font-size: 11px; text-align: left; white-space: nowrap;">${process}</td>
              <td style="padding: 4px 0; color: #52c41a; font-weight: bold; font-size: 11px; text-align: right; white-space: nowrap;">${count}次 (${percentage}%)</td>
            </tr>`
          }
        })
        
        result += `</table>`
        result += `<div style="margin-top: 6px; padding-top: 4px; border-top: 1px solid rgba(0, 212, 255, 0.4); font-size: 10px; color: rgba(255, 255, 255, 0.6); text-align: center;">
          工艺流程时序统计
        </div>`
        
        return result
      }
    },
    radar: {
      indicator: stats.processes.map(process => ({
        name: process,
        max: maxValue
      })),
      radius: '60%',
      center: ['50%', '55%'],
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(24, 144, 255, 0.02)', 'rgba(24, 144, 255, 0.05)']
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.2)'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.2)'
        }
      },
      name: {
        textStyle: {
          color: 'rgba(255, 255, 255, 0.65)',
          fontSize: 10
        }
      }
    },
    series: [{
      type: 'radar',
      tooltip: {
        trigger: 'item'
      },
      data: [{
        value: stats.counts,
        name: '工序出现次数',
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          color: '#52c41a',
          width: 2
        },
        areaStyle: {
          color: 'rgba(82, 196, 26, 0.2)'
        },
        itemStyle: {
          color: '#52c41a',
          borderColor: '#ffffff',
          borderWidth: 2
        },
        emphasis: {
          lineStyle: {
            width: 4
          },
          itemStyle: {
            color: '#52c41a',
            borderColor: '#ffffff',
            borderWidth: 3,
            shadowBlur: 15,
            shadowColor: 'rgba(82, 196, 26, 0.6)'
          },
          areaStyle: {
            color: 'rgba(82, 196, 26, 0.4)'
          }
        }
      }]
    }]
  })
}

const initProductionDiffChart = () => {
  if (!productionDiffChart.value) return
  productionDiffChartInstance = echarts.init(productionDiffChart.value)
  updateProductionDiffChart()
}

const updateProductionDiffChart = () => {
  if (!productionDiffChartInstance) return
  
  const stats = weeklyProductionDiffStats.value
  
  productionDiffChartInstance.setOption({
    grid: {
      top: '10%',
      left: '10%',
      right: '8%',
      bottom: '25%'
    },
    xAxis: {
      type: 'category',
      data: stats.dates,
      axisLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.3)'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.65)',
        fontSize: 10,
        rotate: 0,
        margin: 5,
        interval: 0
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.3)'
        }
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: 'rgba(24, 144, 255, 0.1)',
          type: 'dashed'
        }
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.65)',
        fontSize: 10
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(10, 47, 90, 0.95)',
      borderColor: 'rgba(0, 212, 255, 0.6)',
      borderWidth: 2,
      borderRadius: 8,
      padding: [10, 15],
      textStyle: {
        color: '#ffffff',
        fontSize: 12
      },
      formatter: function(params: any) {
        if (params && params.length > 0) {
          const param = params[0]
          const value = param.value
          const date = param.axisValue
          
          return `<div style="font-weight: bold; color: #00d4ff; margin-bottom: 8px;">${date} 生产均差</div>
                  <div style="color: ${value >= 0 ? '#f5222d' : '#52c41a'}; font-size: 14px; font-weight: bold;">
                    ${value >= 0 ? '欠产' : '超产'} ${Math.abs(value)} 件
                  </div>
                  <div style="margin-top: 6px; font-size: 11px; color: rgba(255, 255, 255, 0.7);">
                    ${value >= 0 ? '实际产量低于计划' : '实际产量超过计划'}
                  </div>`
        }
        return ''
      }
    },
    series: [{
      data: stats.differences,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        color: '#52c41a',
        width: 2
      },
      itemStyle: {
        color: function(params: any) {
          // 根据数值正负显示不同颜色：正数（欠产）红色，负数（超产）绿色
          return params.value >= 0 ? '#f5222d' : '#52c41a'
        }
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(82, 196, 26, 0.3)'
          }, {
            offset: 1,
            color: 'rgba(82, 196, 26, 0)'
          }]
        }
      }
    }]
  })
}

// 定时器
let timer: number
let dataRefreshTimer: number

// 刷新所有数据的函数
const refreshAllData = async () => {
  try {
    console.log(`${new Date().toLocaleTimeString()} - 开始刷新所有数据...`)
    
    // 并行获取所有数据以提高性能
    await Promise.allSettled([
      getNowTeamledger(),        // 获取当前班组信息
      getTicketLedger(),         // 获取工单台账数据
      getSigningWork(),          // 获取报工信息数据
      GetTicketLedgerOperational() // 获取工单工艺路线数据
    ])
    
    console.log(`${new Date().toLocaleTimeString()} - 数据刷新完成`)
  } catch (error) {
    console.error('数据刷新过程中发生错误:', error)
  }
}

// 生命周期钩子
onMounted(() => {
  // 初始化所有图表
  initDefectChart()
  initTotalProgressChart()
  initTodayProgressChart()
  initKeyProcessChart()
  initProductionDiffChart()

  // 更新时间（班组信息会通过计算属性自动更新）
  timer = window.setInterval(() => {
    const now = new Date()
    currentTime.value = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日-${now.getHours()}时${now.getMinutes()}分${now.getSeconds()}秒`
  }, 1000)

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)

  // 初始加载数据
  refreshAllData()
  
  // 启动数据刷新定时器，每10秒刷新一次
  dataRefreshTimer = window.setInterval(() => {
    refreshAllData()
  }, 10000)
  
  // 设置数据监听，当数据变化时更新图表
  watch(
    () => getTicketLedgerData.value,
    () => {
      updateTotalProgressChart()
      updateTodayProgressChart()
    },
    { deep: true, immediate: true }
  )
  
  // 监听报工数据变化，更新不良品统计图表
  watch(
    () => getSigningWorkData.value,
    () => {
      updateDefectChart()
    },
    { deep: true, immediate: true }
  )
  
  // 监听班组数据变化，更新产量均差图表
  watch(
    () => getNowTeamledgerData.value,
    () => {
      // 班组数据变化时更新产量均差图表
      updateProductionDiffChart()
    },
    { deep: true, immediate: true }
  )
  
  // 监听工单工艺路线数据变化，更新关键工序雷达图
  watch(
    () => GetTicketLedgerOperationalData.value,
    () => {
      updateKeyProcessChart()
    },
    { deep: true, immediate: true }
  )
})



onUnmounted(() => {
  // 清理定时器
  clearInterval(timer)
  clearInterval(dataRefreshTimer)
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  defectChartInstance?.dispose()
  totalProgressChartInstance?.dispose()
  todayProgressChartInstance?.dispose()
  keyProcessChartInstance?.dispose()
  productionDiffChartInstance?.dispose()
})

// 窗口大小变化处理
const handleResize = () => {
  defectChartInstance?.resize()
  totalProgressChartInstance?.resize()
  todayProgressChartInstance?.resize()
  keyProcessChartInstance?.resize()
  productionDiffChartInstance?.resize()
}

//-----------------------------------------------------------------------------------------
//--班组---
const getNowTeamledgerData = ref<TeamScheduleData[]>([])
const getNowTeamledger = () => {
  http.get('api/TeamManagement/GetNowTeamledger').then(res => {
    getNowTeamledgerData.value = res.data
  })
}

// 根据当前时间获取当前班组信息
const getCurrentTeamInfo = computed(() => {
  if (!getNowTeamledgerData.value || getNowTeamledgerData.value.length === 0) {
    return null
  }

  const now = new Date()
  const currentTimeStr = now.toTimeString().slice(0, 5) // 格式: HH:MM
  const currentDateStr = now.toISOString().slice(0, 10) // 格式: YYYY-MM-DD

  // 遍历所有班组数据，找到当前时间段内工作的班组
  for (const teamData of getNowTeamledgerData.value) {
    // 检查班组基本信息是否完整
    if (!teamData.team && !teamData.teamName) {
      continue
    }
    
    // 使用准确的API字段名（小写开头）
    const shifts = [
      {
        start: teamData.morningshiftStarttim,     // 早班
        end: teamData.morningshiftEndtime,
        type: 'morning'
      },
      {
        start: teamData.firstmorningShiftStarttime, // 早班1
        end: teamData.firstmorningShiftEndtime,
        type: 'firstMorning'
      },
      {
        start: teamData.middleShiftStartTime,      // 中班
        end: teamData.middleShiftEndTime,
        type: 'middle'
      },
      {
        start: teamData.firstmiddleShiftStartTim,  // 中班1
        end: teamData.firstmiddleShiftEndTime,
        type: 'firstMiddle'
      },
      {
        start: teamData.eveningShiftStartTime,     // 晚班
        end: teamData.eveningShiftEndTime,
        type: 'evening'
      },
      {
        start: teamData.firsteveningShiftStartTime, // 晚班1
        end: teamData.firsteveningShiftEndTime,
        type: 'firstEvening'
      }
    ]

    // 检查当前时间是否在任何班次时间段内
    for (const shift of shifts) {
      if (shift.start && shift.end && shift.start !== 'null' && shift.end !== 'null' && shift.start !== '(Null)' && shift.end !== '(Null)') {
        // 提取时间部分，支持多种格式
        const shiftStart = extractTimeFromString(shift.start)
        const shiftEnd = extractTimeFromString(shift.end)

        // 跳过无效的时间
        if (shiftStart === '00:00' && shiftEnd === '00:00') {
          continue
        }

        // 改进日期匹配逻辑 - 考虑跨天班次和当天班次
        const shiftDateObj = extractDateFromString(shift.start)
        const currentDateObj = new Date(currentDateStr)
        const shiftDateObjDate = shiftDateObj ? new Date(shiftDateObj) : currentDateObj
        
        // 如果没有日期信息，或者是当天，或者是昨天到今天的跨天班次
        const dateDiff = Math.abs(currentDateObj.getTime() - shiftDateObjDate.getTime()) / (1000 * 60 * 60 * 24)
        const dateMatches = !shiftDateObj || dateDiff <= 1
        
        if (dateMatches) {
          const timeMatches = isTimeInRange(currentTimeStr, shiftStart, shiftEnd)
          
          if (timeMatches) {
            return {
              name: teamData.team || teamData.teamName || '未知班组',
              memberCount: teamData.teamNum || 0,
              leader: teamData.duty || '未知',
              phone: teamData.phone || '无',
              shiftType: shift.type,
              teamId: teamData.teamId || 0
            }
          }
        }
      }
    }
  }

  // 严格匹配：如果当前时间不在任何班次时间段内，返回null
  return null
})

// 判断当前时间是否在指定时间范围内
const isTimeInRange = (currentTime: string, startTime: string, endTime: string): boolean => {
  if (!startTime || !endTime) return false
  
  const current = timeToMinutes(currentTime)
  const start = timeToMinutes(startTime)
  const end = timeToMinutes(endTime)

  // 处理跨天的情况（如夜班）
  if (start > end) {
    return current >= start || current <= end
  } else {
    return current >= start && current <= end
  }
}

// 将时间字符串转换为分钟数（便于比较）
const timeToMinutes = (timeStr: string): number => {
  if (!timeStr || timeStr === '00:00') return 0
  
  try {
    const parts = timeStr.split(':')
    if (parts.length < 2) return 0
    
    const hours = parseInt(parts[0]) || 0
    const minutes = parseInt(parts[1]) || 0
    
    return hours * 60 + minutes
  } catch (error) {
    console.error('时间转换错误:', timeStr, error)
    return 0
  }
}

// 从各种格式的字符串中提取时间部分 (HH:MM)
const extractTimeFromString = (timeStr: string): string => {
  if (!timeStr) return '00:00'
  
  try {
    // 如果是null字符串
    if (timeStr === 'null' || timeStr === '(Null)' || timeStr === 'undefined' || timeStr.toLowerCase() === 'null') {
      return '00:00'
    }
    
    // 如果包含T，说明是ISO格式，如 "2025-06-07T06:00:00"
    if (timeStr.includes('T')) {
      return new Date(timeStr).toTimeString().slice(0, 5)
    }
    
    // 如果包含空格，说明是日期时间格式，如 "2025-06-07 06:00:00"
    if (timeStr.includes(' ')) {
      const timePart = timeStr.split(' ')[1]
      return timePart ? timePart.slice(0, 5) : '00:00'
    }
    
    // 如果只是时间格式，如 "06:00:00" 或 "06:00"
    if (timeStr.includes(':')) {
      return timeStr.slice(0, 5)
    }
    
    return '00:00'
  } catch (error) {
    console.error('时间提取错误:', timeStr, error)
    return '00:00'
  }
}

// 从各种格式的字符串中提取日期部分 (YYYY-MM-DD)
const extractDateFromString = (dateStr: string): string | null => {
  if (!dateStr) return null
  
  // 如果包含T，说明是ISO格式，如 "2025-06-07T06:00:00"
  if (dateStr.includes('T')) {
    return new Date(dateStr).toISOString().slice(0, 10)
  }
  
  // 如果包含空格，说明是日期时间格式，如 "2025-06-07 06:00:00"
  if (dateStr.includes(' ')) {
    const datePart = dateStr.split(' ')[0]
    return datePart || null
  }
  
  // 如果是日期格式，如 "2025-06-07"
  if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
    return dateStr
  }
  
  return null
}

// 获取班次类型的中文名称
const getShiftTypeName = (shiftType: string): string => {
  const shiftNames: Record<string, string> = {
    morning: '早班',
    firstMorning: '早班前段',
    middle: '中班',
    firstMiddle: '中班前段',
    evening: '晚班',
    firstEvening: '晚班前段'
  }
  return shiftNames[shiftType] || '未知班次'
}
//-----------------------------------------------------------
//----每日工单台账（用于近期生产计划列表）
const getTicketLedgerData = ref<TicketLedgerData[]>([])

const getTicketLedger = () => {
  http.get('api/Operation/GetTicketLedger').then(res => {
    getTicketLedgerData.value = res.data
  })
}

// 计算订单总体进度数据
const totalOrderStats = computed(() => {
  if (!getTicketLedgerData.value || getTicketLedgerData.value.length === 0) {
    return {
      totalPlan: 0,
      produced: 0,
      defects: 0,
      completionRate: 0
    }
  }

  const totalPlan = getTicketLedgerData.value.reduce((sum, ticket) => sum + (ticket.plan || 0), 0)
  const produced = getTicketLedgerData.value.reduce((sum, ticket) => sum + (ticket.produce || 0), 0)
  const defects = getTicketLedgerData.value.reduce((sum, ticket) => sum + (ticket.defectiveProduct || 0), 0)
  const completionRate = totalPlan > 0 ? Math.round((produced / totalPlan) * 100) : 0

  return { totalPlan, produced, defects, completionRate }
})

// 计算订单今日进度数据
const todayOrderStats = computed(() => {
  if (!getTicketLedgerData.value || getTicketLedgerData.value.length === 0) {
    return {
      todayPlan: 0,
      todayProduced: 0,
      todayDefects: 0,
      qualityRate: 0
    }
  }

  const today = new Date().toISOString().slice(0, 10) // YYYY-MM-DD

  // 筛选今天的订单（根据开始时间判断）
  const todayTickets = getTicketLedgerData.value.filter(ticket => {
    if (!ticket.stateTime) return false
    const ticketDate = new Date(ticket.stateTime).toISOString().slice(0, 10)
    return ticketDate === today
  })

  const todayPlan = todayTickets.reduce((sum, ticket) => sum + (ticket.plan || 0), 0)
  const todayProduced = todayTickets.reduce((sum, ticket) => sum + (ticket.produce || 0), 0)
  const todayDefects = todayTickets.reduce((sum, ticket) => sum + (ticket.defectiveProduct || 0), 0)
  const qualityRate = todayProduced > 0 ? Math.round(((todayProduced - todayDefects) / todayProduced) * 100) : 0

  return { todayPlan, todayProduced, todayDefects, qualityRate }
})

// 计算工单进度百分比
const calculateProgress = (produce: number, plan: number): number => {
  if (plan === 0) return 0
  return Math.round((produce / plan) * 100)
}

// 获取状态显示样式类名
const getStatusClass = (state: any): string => {
  // 处理各种可能的状态格式
  let statusCode: number
  
  if (typeof state === 'number') {
    statusCode = state
  } else if (typeof state === 'string') {
    statusCode = parseInt(state)
  } else {
    return 'default'
  }
  
  const statusMap: Record<number, string> = {
    0: 'created',      // 创建
    1: 'in-progress',  // 进行中
    2: 'completed'     // 已完成
  }
  
  return statusMap[statusCode] || 'default'
}

// 获取状态显示文本
const getStatusText = (state: any): string => {
  // 处理各种可能的状态格式
  let statusCode: number
  
  if (typeof state === 'number') {
    statusCode = state
  } else if (typeof state === 'string') {
    statusCode = parseInt(state)
  } else {
    return '未知状态'
  }
  
  const statusMap: Record<number, string> = {
    0: '创建',
    1: '进行中', 
    2: '已完成'
  }
  
  return statusMap[statusCode] || '未知状态'
}

// 处理工单数据，用于表格显示（替换原来的静态数据）
const processedTicketData = computed(() => {
  if (!getTicketLedgerData.value || getTicketLedgerData.value.length === 0) {
    return []
  }
  
  // 转换数据格式以匹配现有的表格结构
  return getTicketLedgerData.value.map((ticket, index) => ({
    id: ticket.tickeId,
    orderId: ticket.tickeNumber,           // 工单编号 -> 订单列
    quantity: ticket.plan,                 // 计划数量 -> 数量列
    startTime: new Date(ticket.stateTime), // 开始时间 -> 开始列
    endTime: new Date(ticket.endTime),     // 结束时间 -> 结束列
    status: getStatusClass(ticket.ordersState),  // 状态样式类（使用正确的字段名 ordersState）
    statusText: getStatusText(ticket.ordersState), // 状态文本（使用正确的字段名 ordersState）
    completionRate: calculateProgress(ticket.produce, ticket.plan), // 计算进度
    duplicate: 1,                          // 用于滚动复制
    // 额外信息
    bomcode: ticket.bomcode,
    line: ticket.line,
    produce: ticket.produce,
    defectiveProduct: ticket.defectiveProduct,
    firstPassRate: ticket.firstPassRate,
    qRCode: ticket.qRCode
  }))
})

// 计算属性：使用真实数据，实现简单的上下滚动效果
const duplicatedPlans = computed(() => {
  const dataToUse = processedTicketData.value.length > 0 ? processedTicketData.value : productionPlans.value
  // 不复制数据，直接使用原始数据
  return dataToUse.map(plan => ({ ...plan, duplicate: 1 }))
})

//-----------------------------------------------------------------
//--------报工信息
const getSigningWorkData = ref<SigningWorkData[]>([])

const getSigningWork = () => {
  http.get('api/TeamManagement/GetSigningWork').then(res => {
    getSigningWorkData.value = res.data
  })
}

// 计算近一周不良品统计数据
const weeklyDefectStats = computed(() => {
  if (!getSigningWorkData.value || getSigningWorkData.value.length === 0) {
    // 生成默认的近7天日期
    const today = new Date()
    const defaultDates: string[] = []
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(today.getDate() - i)
      defaultDates.push(formatDateForChart(date))
    }
    return {
      dates: defaultDates,
      defectCounts: [0, 0, 0, 0, 0, 0, 0]
    }
  }

  // 获取近7天的日期
  const today = new Date()
  const last7Days: string[] = []
  const last7DaysFormatted: string[] = []
  
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(today.getDate() - i)
    last7Days.push(date.toISOString().slice(0, 10)) // YYYY-MM-DD格式，用于数据匹配
    last7DaysFormatted.push(formatDateForChart(date)) // MM/DD格式，用于图表显示
  }

  // 按日期统计不良品数量
  const defectCountsByDate: Record<string, number> = {}
  
  getSigningWorkData.value.forEach(item => {
    if (item.createTime && item.defective > 0) {
      const itemDate = new Date(item.createTime).toISOString().slice(0, 10)
      if (last7Days.includes(itemDate)) {
        defectCountsByDate[itemDate] = (defectCountsByDate[itemDate] || 0) + item.defective
      }
    }
  })

  // 生成图表数据
  const dates = last7DaysFormatted // 使用格式化的日期
  const defectCounts = last7Days.map(date => defectCountsByDate[date] || 0)

  return { dates, defectCounts }
})

// 格式化日期用于图表显示
const formatDateForChart = (date: Date): string => {
  const month = date.getMonth() + 1
  const day = date.getDate()
  
  // 如果是今天，特别标注
  const today = new Date()
  const isToday = date.toDateString() === today.toDateString()
  
  if (isToday) {
    return `${month}/${day}(今)`
  } else {
    return `${month}/${day}`
  }
}

// 计算近一周的生产均差数据（基于班组数据）
const weeklyProductionDiffStats = computed(() => {
  if (!getNowTeamledgerData.value || getNowTeamledgerData.value.length === 0) {
    console.log('班组数据为空，使用默认产量均差数据')
    // 生成默认的近7天日期
    const today = new Date()
    const defaultDates: string[] = []
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(today.getDate() - i)
      defaultDates.push(formatDateForChart(date))
    }
    return {
      dates: defaultDates,
      differences: [0, 0, 0, 0, 0, 0, 0]
    }
  }

  // 获取近7天的日期
  const today = new Date()
  const last7Days: string[] = []
  const last7DaysFormatted: string[] = []
  
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(today.getDate() - i)
    last7Days.push(date.toISOString().slice(0, 10)) // YYYY-MM-DD格式，用于数据匹配
    last7DaysFormatted.push(formatDateForChart(date)) // MM/DD格式，用于图表显示
  }

  // 按日期统计生产均差（计划产量 - 实际产量）
  const diffByDate: Record<string, number> = {}
  
  console.log('开始统计班组生产均差数据，总记录数:', getNowTeamledgerData.value.length)
  
  getNowTeamledgerData.value.forEach((item, index) => {
    // 尝试从不同字段获取数据
    const planProduction = item.yield || item.plan || 0  // 计划产量
    const actualProduction = item.actual || item.produce || 0  // 实际产量
    const createTime = item.createTime || item.targetTime  // 创建日期
    
    console.log(`记录${index}:`, {
      计划产量: planProduction,
      实际产量: actualProduction,
      创建时间: createTime,
      原始数据: item
    })
    
    if (createTime && (planProduction > 0 || actualProduction > 0)) {
      try {
        const itemDate = new Date(createTime).toISOString().slice(0, 10)
        
        if (last7Days.includes(itemDate)) {
          const difference = planProduction - actualProduction  // 计算均差
          
          // 如果该日期已有数据，累加差值
          diffByDate[itemDate] = (diffByDate[itemDate] || 0) + difference
          
          console.log(`日期${itemDate}: 计划${planProduction} - 实际${actualProduction} = 差值${difference}, 累计差值${diffByDate[itemDate]}`)
        }
      } catch (error) {
        console.error('解析日期失败:', createTime, error)
      }
    }
  })

  console.log('生产均差统计结果:', diffByDate)

  // 生成图表数据
  const dates = last7DaysFormatted
  const differences = last7Days.map(date => diffByDate[date] || 0)

  console.log('最终图表数据:', { dates, differences })

  return { dates, differences }
})
//--------------------------------------
//工单与工艺路线
const GetTicketLedgerOperationalData = ref<TicketLedgerOperationalData[]>([])
const GetTicketLedgerOperational = () => {
  http.get('api/Operation/GetTicketLedgerOperational').then(res => {
    GetTicketLedgerOperationalData.value = res.data
  })
}

// 计算工艺流程统计（使用所有数据，显示真实的工序统计）
const processTimingStats = computed(() => {
  if (!GetTicketLedgerOperationalData.value || GetTicketLedgerOperationalData.value.length === 0) {
    console.log('工艺路线数据为空')
    return {
      processes: ['暂无数据'],
      counts: [0]
    }
  }

  const processCount: Record<string, number> = {}
  let totalRecords = 0
  let validRecords = 0

  console.log('开始统计工艺流程数据，总记录数:', GetTicketLedgerOperationalData.value.length)

  // 统计所有数据中的工序（不限制时间范围，使用所有数据）
  GetTicketLedgerOperationalData.value.forEach((item, index) => {
    totalRecords++
    const processTiming = item.processTiming || item.ProcessTiming
    
    if (!processTiming) {
      console.log(`记录${index}：缺少processTiming字段`, item)
      return
    }

    validRecords++
    console.log(`记录${index}：processTiming = "${processTiming}"`)

    try {
      // 解析 processTiming 字段，按多种分隔符分割
      const processes = processTiming
        .split(/[,，、;；\s]+/) // 支持更多分隔符：逗号、分号、空格等
        .map((process: string) => process.trim())
        .filter((process: string) => process.length > 0)
      
      console.log(`记录${index}：分割出的工序:`, processes)
      
      // 统计每个工序出现的次数
      processes.forEach((process: string) => {
        processCount[process] = (processCount[process] || 0) + 1
      })
    } catch (error) {
      console.error('解析工艺流程数据错误:', error, item)
    }
  })

  console.log('统计完成 - 总记录数:', totalRecords, '有效记录数:', validRecords)
  console.log('工序统计结果:', processCount)

  // 获取所有工序，按出现次数排序
  const sortedProcesses = Object.entries(processCount)
    .sort(([, a], [, b]) => b - a)
    .filter(([, count]) => count > 0) // 只显示有数据的工序

  if (sortedProcesses.length === 0) {
    console.log('没有找到有效的工序数据')
    return {
      processes: ['暂无数据'],
      counts: [0]
    }
  }

  const processes = sortedProcesses.map(([process]) => process)
  const counts = sortedProcesses.map(([, count]) => count)

  console.log('最终显示的工序:', processes)
  console.log('最终显示的次数:', counts)

  return { processes, counts }
})

</script>
<style scoped>
/* 保持原有布局,只修改视觉样式 */
.dashboard {
  padding: 16px;
  background: linear-gradient(125deg, #000000, #1a0f2e);
  position: relative;
  height: calc(100vh - 120px);
  max-height: calc(100vh - 120px);
  overflow: hidden;
  color: #fff;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

/* 背景网格效果 */
.dashboard::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    linear-gradient(rgba(255, 0, 140, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 0, 140, 0.1) 1px, transparent 1px);
  background-size: 20px 20px;
  background-position: center center;
  opacity: 0.3;
}

/* 背景光效 */
.dashboard::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 30% 20%, rgba(255, 0, 140, 0.4) 0%, transparent 50%),
    radial-gradient(circle at 70% 80%, rgba(128, 0, 255, 0.4) 0%, transparent 50%);
  filter: blur(120px);
  opacity: 0.15;
  z-index: 0;
}

.dashboard-header {
  position: relative;
  margin-bottom: 20px;
  padding: 0;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dashboard-title {
  font-size: 32px;
  font-weight: 800;
  text-transform: uppercase;
  background: linear-gradient(90deg, #ff0088, #7000ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 4px;
  position: relative;
  text-shadow: none;
  filter: drop-shadow(0 0 15px rgba(255, 0, 136, 0.5));
}

/* 标题装饰 */
.header-decoration-left,
.header-decoration-right {
  position: absolute;
  top: 50%;
  width: 160px;
  height: 2px;
  background: linear-gradient(90deg, transparent, #ff0088, transparent);
  transform: translateY(-50%);
}

.header-decoration-left {
  left: 20%;
  transform: translateY(-50%) rotate(-15deg);
}

.header-decoration-right {
  right: 20%;
  transform: translateY(-50%) rotate(15deg);
}

.chart-card, .info-card, .table-card {
  background: rgba(20, 10, 38, 0.7);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 0, 140, 0.2);
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}

/* 卡片发光边框效果 */
.chart-card::before,
.info-card::before,
.table-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 1px solid transparent;
  border-radius: 4px;
  background: linear-gradient(135deg, #ff0088, #7000ff) border-box;
  -webkit-mask:
    linear-gradient(#fff 0 0) padding-box,
    linear-gradient(#fff 0 0);
  -webkit-mask-composite: destination-out;
  mask-composite: exclude;
  opacity: 0.3;
  transition: opacity 0.3s ease;
}

.chart-card:hover::before,
.info-card:hover::before,
.table-card:hover::before {
  opacity: 1;
}

.card-title {
  color: #ff0088;
  font-size: 16px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 0, 140, 0.2);
}

/* 表格样式 */
.table-header-row {
  background: rgba(255, 0, 140, 0.1);
  backdrop-filter: blur(5px);
  border: none;
}

.table-row {
  border-bottom: 1px solid rgba(255, 0, 140, 0.1);
  transition: all 0.3s ease;
}

.table-row:hover {
  background: rgba(255, 0, 140, 0.05);
  transform: scale(1.01);
}

.header-cell {
  color: #ff0088;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
  font-size: 12px;
}

.table-cell {
  color: rgba(255, 255, 255, 0.9);
}

/* 状态样式 */
.created { color: #ff0088; }
.in-progress { color: #7000ff; }
.completed { color: #00ffbb; }

/* 按钮样式 */
.plan-button {
  background: linear-gradient(45deg, #ff0088, #7000ff);
  border: none;
  color: white;
  padding: 8px 20px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.plan-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.2),
    transparent
  );
  transition: 0.5s;
}

.plan-button:hover::before {
  left: 100%;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 0, 140, 0.1);
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(#ff0088, #7000ff);
  border-radius: 2px;
}

/* 进度条和图表颜色 */
.progress-chart .completed { color: #ff0088; }
.progress-chart .remaining { color: rgba(255, 0, 140, 0.2); }

.rate-dot.success { background: #00ffbb; }
.rate-dot.warning { background: #ffbb00; }
.rate-dot.danger { background: #ff0088; }
.rate-dot.info { background: #7000ff; }

/* 动画效果 */
@keyframes glow {
  0% { box-shadow: 0 0 5px rgba(255, 0, 140, 0.5); }
  50% { box-shadow: 0 0 20px rgba(255, 0, 140, 0.8); }
  100% { box-shadow: 0 0 5px rgba(255, 0, 140, 0.5); }
}

/* 异常列表样式 */
.exception-item {
  background: linear-gradient(135deg, rgba(255, 0, 140, 0.1), rgba(112, 0, 255, 0.1));
  border: 1px solid rgba(255, 0, 140, 0.2);
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.exception-item:hover {
  transform: translateX(5px);
  background: linear-gradient(135deg, rgba(255, 0, 140, 0.2), rgba(112, 0, 255, 0.2));
  border-color: rgba(255, 0, 140, 0.4);
}

.dashboard-time {
  position: absolute;
  right: 15px;
  font-size: 14px;
  color: #00d4ff;
  font-weight: 500;
}

.dashboard-content {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  max-height: calc(100vh - 180px);
  overflow: hidden;
}

.load-plan-container {
  display: flex;
  align-items: center;
  gap: 0;
  margin-bottom: 15px;
  flex-shrink: 0;
  height: 40px;
  width: calc((100% - 24px) * 1 / 4);
}

.plan-input-area {
  flex: 1;
  height: 100%;
  background: rgba(0, 21, 41, 0.6);
  border: 1px solid rgba(24, 144, 255, 0.2);
  border-right: none;
  border-radius: 8px 0 0 8px;
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  position: relative;
  box-shadow: inset 0 0 15px rgba(24, 144, 255, 0.05);
  transition: all 0.3s ease;
}

.plan-input-area:hover {
  border-color: rgba(24, 144, 255, 0.4);
  box-shadow: inset 0 0 20px rgba(24, 144, 255, 0.1);
}

.plan-input {
  width: 100%;
  height: 100%;
  background: transparent;
  border: none;
  outline: none;
  color: #fff;
  padding: 0 15px;
  font-size: 13px;
}

.plan-button {
  background: linear-gradient(90deg, #1890ff, #40a9ff);
  border: 1px solid rgba(24, 144, 255, 0.2);
  border-left: none;
  color: white;
  padding: 0 20px;
  border-radius: 0 8px 8px 0;
  font-size: 13px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.plan-button:hover {
  background: linear-gradient(90deg, #40a9ff, #69c0ff);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.status-tag {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  background: rgba(24, 144, 255, 0.1);
  border: 1px solid rgba(24, 144, 255, 0.2);
  transition: all 0.3s ease;
}

.status-tag:hover {
  background: rgba(24, 144, 255, 0.15);
  border-color: rgba(24, 144, 255, 0.3);
  transform: translateY(-1px);
}

.exception-item {
  background: rgba(0, 21, 41, 0.4);
  border: 1px solid rgba(24, 144, 255, 0.2);
  border-radius: 12px;
  padding: 12px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.exception-item:hover {
  background: rgba(24, 144, 255, 0.1);
  border-color: rgba(24, 144, 255, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: rgba(24, 144, 255, 0.05);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: rgba(24, 144, 255, 0.2);
  border-radius: 3px;
  transition: all 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(24, 144, 255, 0.3);
}

.rate-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 8px;
}

.rate-dot.success { background-color: #52c41a; }
.rate-dot.warning { background-color: #faad14; }
.rate-dot.danger { background-color: #f5222d; }
.rate-dot.info { background-color: #1890ff; }

.progress-chart .completed { color: #1890ff; }
.progress-chart .remaining { color: rgba(24, 144, 255, 0.2); }

.product-quality.good { color: #52c41a; }
.product-quality.bad { color: #f5222d; }
.product-quality.unknown { color: #faad14; }

/* 主要布局 - 三列结构 */
.main-layout {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 12px;
  flex: 1;
  min-height: 0;
  max-height: 100%;
  overflow: hidden;
  z-index: 1;
}

/* 左侧区域 */
.left-section {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  gap: 12px;
  overflow: hidden;
}

/* 关键工序和生产率评估左右布局 */
.process-rate-row {
  display: grid;
  grid-template-columns: 1.2fr 0.8fr;
  gap: 12px;
  overflow: hidden;
}

/* 中间区域 */
.center-section {
  display: grid;
  grid-template-rows: 0.7fr 1.5fr;
  gap: 12px;
  overflow: hidden;
}

.progress-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  overflow: hidden;
}

/* 右侧区域 */
.right-section {
  display: grid;
  grid-template-rows: 0.8fr 0.8fr 1.4fr;
  gap: 12px;
  overflow: hidden;
}

.chart-card, .info-card, .table-card {
  background: linear-gradient(145deg, rgba(10, 47, 90, 0.8), rgba(15, 60, 120, 0.6));
  border-radius: 16px;
  padding: 12px;
  border: 1px solid rgba(0, 212, 255, 0.3);
  position: relative;
  backdrop-filter: blur(15px);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.4),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 0;
  transition: all 0.3s ease;
}

.chart-card:hover, .info-card:hover, .table-card:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 40px rgba(0, 0, 0, 0.5),
    0 0 20px rgba(0, 212, 255, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.15);
  border-color: rgba(0, 212, 255, 0.5);
}

/* 给表格卡片特殊样式 */
.table-card {
  padding: 10px;
  background: linear-gradient(145deg, rgba(10, 47, 90, 0.9), rgba(15, 60, 120, 0.7));
}

.table-card .card-title {
  margin-bottom: 8px;
  padding: 0;
}

.chart-card::before,
.info-card::before,
.table-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, transparent, #00d4ff, #52c41a, #00d4ff, transparent);
  border-radius: 16px 16px 0 0;
  animation: topBorderFlow 3s ease-in-out infinite;
}

@keyframes topBorderFlow {
  0%, 100% { 
    background: linear-gradient(90deg, transparent, #00d4ff, #52c41a, #00d4ff, transparent);
  }
  50% { 
    background: linear-gradient(90deg, transparent, #52c41a, #00d4ff, #52c41a, transparent);
  }
}

.card-title {
  font-size: 16px;
  margin-bottom: 8px;
  color: #00d4ff;
  border-bottom: 2px solid rgba(0, 212, 255, 0.3);
  padding-bottom: 6px;
  font-weight: 600;
  flex-shrink: 0;
  line-height: 1.3;
  text-shadow: 0 0 10px rgba(0, 212, 255, 0.5);
  position: relative;
}

.card-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, #00d4ff, #52c41a);
  transition: width 0.3s ease;
}

.chart-card:hover .card-title::after,
.info-card:hover .card-title::after,
.table-card:hover .card-title::after {
  width: 100%;
}

.chart {
  flex: 1;
  min-height: 0;
}

.chart-small {
  height: 90px;
  position: relative;
}

.progress-chart-wrapper {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.progress-chart-container {
  position: relative;
  height: 90px;
  flex-shrink: 0;
}

.progress-center-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  pointer-events: none;
}

.center-label {
  font-size: 12px;
  color: #00d4ff;
  font-weight: 500;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  margin-top: 6px;
  flex: 1;
}

.info-left,
.info-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-left > div,
.info-right > div {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  padding: 1px 0;
  line-height: 1.3;
}

.team-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.team-info p {
  margin: 3px 0;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.85);
  line-height: 1.4;
}

.no-team-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 80px;
}

.no-team-info p {
  margin: 2px 0;
  color: rgba(0, 212, 255, 0.6);
  font-size: 12px;
  line-height: 1.2;
}

.exception-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 6px;
}

.exception-item {
  padding: 8px 12px;
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.15), rgba(24, 144, 255, 0.1));
  border-radius: 20px;
  font-size: 12px;
  border: 1px solid rgba(0, 212, 255, 0.4);
  color: #00d4ff;
  text-align: center;
  min-width: 60px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 212, 255, 0.2);
  backdrop-filter: blur(10px);
}

.exception-item:hover {
  transform: translateY(-1px) scale(1.02);
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.25), rgba(24, 144, 255, 0.2));
  box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
  border-color: rgba(0, 212, 255, 0.6);
}

.production-rate {
  display: flex;
  flex-direction: column;
  gap: 6px;
  justify-content: center;
  flex: 1;
}

.rate-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.85);
  line-height: 1.3;
}

.rate-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.rate-dot.success {
  background-color: #52c41a;
}

.rate-dot.warning {
  background-color: #faad14;
}

.rate-dot.danger {
  background-color: #f5222d;
}

.rate-dot.info {
  background-color: #1890ff;
}

.table-container {
  overflow-y: auto;
  flex: 1;
  min-height: 0;
  width: 100%;
  box-sizing: border-box;
}

/* 滚动表格样式 */
.scrolling-table {
  overflow: hidden !important;
  position: relative;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-header {
  position: relative;
  z-index: 2;
  background-color: rgba(10, 47, 90, 0.6);
  flex-shrink: 0;
}

.table-header-row {
  display: grid;
  grid-template-columns: 1fr 0.8fr 1.5fr 1.5fr 0.8fr 0.7fr;
  gap: 8px;
  padding: 10px 8px;
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.15), rgba(24, 144, 255, 0.1));
  border-bottom: 2px solid rgba(0, 212, 255, 0.3);
  border-radius: 12px 12px 0 0;
  white-space: nowrap;
  width: 100%;
  box-sizing: border-box;
  backdrop-filter: blur(10px);
}

.header-cell {
  color: #00d4ff;
  font-weight: 500;
  font-size: 11px;
  text-align: left;
  line-height: 1.2;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;
}

.table-body {
  flex: 1;
  overflow: hidden;
  position: relative;
  min-height: 0;
}

.scrolling-content {
  animation: scrollUp 20s linear infinite;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 0.8fr 1.5fr 1.5fr 0.8fr 0.7fr;
  gap: 8px;
  padding: 6px;
  border-bottom: 1px solid rgba(0, 212, 255, 0.1);
  min-height: 28px;
  align-items: center;
}

.table-cell {
  color: rgba(255, 255, 255, 0.85);
  font-size: 11px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

/* 滚动动画 */
@keyframes scrollUp {
  0% {
    transform: translateY(100%);
  }
  100% {
    transform: translateY(-100%);
  }
}

/* 当鼠标悬停时暂停动画 */
.scrolling-table:hover .scrolling-content {
  animation-play-state: paused;
}

/* 产品列表表头样式 */
.product-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.product-list .table-header-row {
  display: grid;
  grid-template-columns: 1.2fr 0.8fr 1fr;
  gap: 8px;
  padding: 8px 6px;
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.15), rgba(24, 144, 255, 0.1));
  color: #00d4ff;
  font-weight: 500;
  font-size: 12px;
  border-bottom: 2px solid rgba(0, 212, 255, 0.3);
  border-radius: 12px 12px 0 0;
  flex-shrink: 0;
  line-height: 1.3;
}

.product-list .table-header-row > span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-item {
  display: grid;
  grid-template-columns: 1.2fr 0.8fr 1fr;
  gap: 8px;
  padding: 8px 6px;
  border-bottom: 1px solid rgba(0, 212, 255, 0.1);
  color: rgba(255, 255, 255, 0.85);
  font-size: 11px;
  line-height: 1.3;
  min-height: 28px;
  align-items: center;
}

.product-item > span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.created {
  color: #faad14;   /* 橙色 - 创建状态 */
}

.in-progress {
  color: #52c41a;   /* 绿色 - 进行中状态 */
}

.completed {
  color: #1890ff;   /* 蓝色 - 已完成状态 */
}

.paused {
  color: #ff7a45;   /* 橘红色 - 暂停状态（备用） */
}

.error {
  color: #f5222d;   /* 红色 - 异常状态（备用） */
}

.default {
  color: rgba(255, 255, 255, 0.8);  /* 默认颜色 */
}

.good {
  color: #52c41a;
}

.defect {
  color: #f5222d;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 212, 255, 0.4);
  border-radius: 2px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 212, 255, 0.6);
}

/* 响应式设计 - 更小的断点 */
@media (max-width: 1000px) {
  .main-layout {
    grid-template-columns: 1fr;
    grid-template-rows: auto auto auto;
    gap: 8px;
  }
  
  .left-section,
  .right-section {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-template-rows: auto;
    gap: 6px;
  }
  
  .progress-row {
    grid-template-columns: 1fr;
    gap: 6px;
  }

  .process-rate-row {
    grid-template-columns: 1fr;
    gap: 6px;
  }
}

@media (max-width: 1200px) {
  .dashboard-title {
    font-size: 22px;
  }
  
  .dashboard {
    padding: 8px;
    height: calc(100vh - 100px);
    max-height: calc(100vh - 100px);
  }
  
  .card-title {
    font-size: 14px;
  }
  
  .chart-card, .info-card, .table-card {
    padding: 8px;
    border-radius: 12px;
  }
  
  .dashboard-header {
    height: 50px;
    max-height: 50px;
  }
  
  .dashboard-content {
    max-height: calc(100vh - 150px);
  }
  
  .main-layout {
    gap: 8px;
    grid-template-columns: 0.8fr 2.2fr 1fr;
  }
  
  .left-section, .center-section, .right-section {
    gap: 8px;
  }
  
  .load-plan-container {
    height: 35px;
    width: calc((100% - 16px) * 0.8 / 2.2);
  }
  
  .plan-button {
    min-width: 80px;
    font-size: 12px;
  }
  
  .plan-input {
    font-size: 12px;
  }
}
</style>